import styles from "./style.module.css";
import { useEffect, useState, useRef } from "react";
import { Button, Switch, Modal } from "antd";
import Player from "../Player";
import Board from "../Board";

const initMap = window.initMap;
const whiteStyle = window.whiteStyle;
const mapvgl = window.mapvgl;

let mapInstance = null; // 地图实例
let mapViewManager = null; // mapvgl 实例

let monitorLayer; // 监控图层
let megaphoneLayer; // 喇叭图层
let sensorLayer;

// 测试使用拉流地址
const pullStreamUrls = [
  "http://192.168.10.122/live?app=demo&stream=a",
  "http://192.168.10.122/live?app=demo&stream=b"
]

/**
 * 地图组件--基于baidu地图 mapvgl
 * @returns 地图组件
 */
const MapV = () => {
  const mapRef = useRef(); // 地图 ref

  const [isModalVisible, setIsModalVisible] = useState(false); // modal
  const [activeObj, setActiveObj] = useState({
    type: "none",
    data: null,
  }); // 点击的图标 对应的对象
  const [views, setViews] = useState({
    monitor: true,
    sensor: true,
    megaphone: true
  }); // 当前显示的图层

  // 地图初始化
  const mapInit = () => {
    // 初始化地图数据
    const map = initMap({
      element: mapRef.current,
      tilt: 60,
      heading: 20,
      center: [122.86558, 40.99124],
      zoom: 17,
      style: whiteStyle,
      skyColors: [
        // 地面颜色
        "rgba(226, 237, 248, 0)",
        // 天空颜色
        "rgba(186, 211, 252, 1)",
      ],
    });

    mapInstance = map;
    window.mapInstance = map;

    // 图层管理器
    const view = new mapvgl.View({
      map: map,
    });
    mapViewManager = view;
    monitorLayer = _renderMonitor(); // 渲染监控
    megaphoneLayer = _renderBoard(); // 渲染喇叭
    sensorLayer = _renderSensor(); // 渲染传感器

    {
      // 渲染边界
    _renderMapBounds(); 

    // 模拟 建筑物
    _renderBuilding();

    // 渲染地块
    _renderTextLayer()
    _renderField()
    }
    
    // 修改界面显示状态
    setViews({
      monitor: true,
      sensor: true,
      megaphone: true
    })
    
  };

  // 渲染地块
  const _renderField = () => {
    const mockDatas = [
      [
        [122.863503, 40.990203],
        [122.862632, 40.991238],
        [122.862142, 40.990958],
        [122.862263, 40.990645],
        [122.862766, 40.989846],
        [122.862928, 40.98975],
        [122.862937, 40.989669],
      ],
      [
        [122.863557, 40.990261],
        [122.862695, 40.991279],
        [122.86344, 40.991667],
        [122.864487, 40.990789],
      ],
      [
        [122.863458, 40.988195],
        [122.865246, 40.989387],
        [122.865677, 40.989101],
        [122.866162, 40.988808],
        [122.866499, 40.988427],
        [122.864145, 40.986698],
        [122.863296, 40.987324],
        [122.863395, 40.987473],
      ],
      [
        [122.866539, 40.988413],
        [122.866835, 40.988399],
        [122.869162, 40.986997],
        [122.869265, 40.986861],
        [122.869288, 40.986752],
        [122.869099, 40.986081],
        [122.869117, 40.985949],
        [122.869185, 40.985796],
        [122.869315, 40.98567],
        [122.869881, 40.985319],
        [122.869831, 40.984812],
        [122.869876, 40.98442],
        [122.869953, 40.984264],
        [122.868811, 40.982987],
        [122.863637, 40.986364],
        [122.864163, 40.986688],
      ],
      [
        [122.867278, 40.990248],
        [122.866811, 40.990466],
        [122.867538, 40.991334],
        [122.869609, 40.990377],
        [122.86801, 40.988989],
        [122.866874, 40.98983],
      ],
      [
        [122.869681, 40.990391],
        [122.871451, 40.989928],
        [122.869762, 40.987804],
        [122.868032, 40.988972],
      ],[
        [122.870193, 40.983999],
        [122.870013, 40.983679],
        [122.869641, 40.983155],
        [122.869328, 40.982783],
        [122.871183, 40.981918],
        [122.872194, 40.983105]
      ],
      [
        [122.870238, 40.984077],
        [122.870815, 40.985178],
        [122.873258, 40.984082],
        [122.872225, 40.983200],
      ],
    ];

    const data = mockDatas.map((mockData, index) => {
      const _data = {};
      _data.geometry = {
        type: 'Polygon',
        coordinates: [mockData]
      }
      _data.properties = {
        height: 0,
        name: `地块 ${index}`
      }
      return _data
    });

    console.log(data)

    // 实例化图层
    const fieldLayer = new mapvgl.ShapeLayer({
      color: 'rgba(55, 55, 200, .4)',
      blend: 'lighter',
      style: 'normal',
      data: data,
      enablePicked: true,
      selectedColor: 'rgba(55, 55, 200, .5)',
      selectedIndex: -1,
      autoSelect: true,
    });
    mapViewManager && mapViewManager.addLayer(fieldLayer)
  };

  // 渲染地块名称
  const _renderTextLayer = () => {
    _renderText("1号田", [122.86268392499198, 40.99055920085688]);
    _renderText("2号田", [122.86356996144532, 40.99085496749627]);
    _renderText("3号田", [122.86499560588628, 40.98812813172233]);
    _renderText("4号田", [122.86765294908149, 40.98594753704951]);
    _renderText("5号田", [122.86809581854874, 40.99022165072747]);
    _renderText("6号田", [122.86995097079132, 40.98931600784661]);
    _renderText("7号田", [122.8708055395128, 40.98296706209733]);
    _renderText("8号田", [122.87163737257097, 40.98399260784581]);
  }

  // 建筑图层
  const _renderBuilding = () => {
    const data = [
      {
        geometry: {
          type: "Polygon",
          coordinates: [
            [
              [122.87080188960769, 40.9882049197848],
              [122.87061712810667, 40.98797060798837],
              [122.87105793048313, 40.987737790007436],
              [122.8712977977272, 40.98794161926156],
            ],
          ],
        },
        properties: {
          height: 20, // 多边形高度
        },
      },
      {
        geometry: {
          type: "Polygon",
          coordinates: [
            [
              [122.87154642102453, 40.988190777199925],
              [122.87118671048307, 40.98851790829696],
              [122.87156504909608, 40.98929898190928],
              [122.8720282012238, 40.9890631553095],
            ],
          ],
        },
        properties: {
          height: 40, // 多边形高度
        },
      },
      {
        geometry: {
          type: "Polygon",
          coordinates: [
            [
              [122.86889604984789, 40.98868108468339],
              [122.8687193087778, 40.98838144197589],
              [122.86963371776149, 40.9878102631834],
              [122.86981302205655, 40.98810620323833],
            ],
          ],
        },
        properties: {
          height: 30, // 多边形高度
        },
      },
      {
        geometry: {
          type: "Polygon",
          coordinates: [
            [
              [122.86528170304477, 40.99056484644862],
              [122.86544840419363, 40.99075459851429],
              [122.86599486715002, 40.99048177556663],
              [122.86583573833265, 40.99029219663482],
            ],
          ],
        },
        properties: {
          height: 10, // 多边形高度
        },
      },
      {
        geometry: {
          type: "Polygon",
          coordinates: [
            [
              [122.86495492976557, 40.99118837993514],
              [122.86468983559293, 40.99079092669669],
              [122.86490988258943, 40.99070708477014],
              [122.86517498487191, 40.99110451220483],
            ],
          ],
        },
        properties: {
          height: 10, // 多边形高度
        },
      },
      {
        geometry: {
          type: "Polygon",
          coordinates: [
            [
              [122.86541022589304, 40.99101325839167],
              [122.8660856265055, 40.99076933386829],
              [122.86599472301984, 40.99063050074599],
              [122.86531933172756, 40.99087439585158],
            ],
          ],
        },
        properties: {
          height: 10, // 多边形高度
        },
      },
      {
        geometry: {
          type: "Polygon",
          coordinates: [
            [
              [122.8667840650387, 40.99031963578],
              [122.8668599683835, 40.9902903880372],
              [122.8667008427297, 40.9900741848356],
              [122.8666249414304, 40.9901034262098],
            ],
          ],
        },
        properties: {
          height: 6, // 多边形高度
        },
      },
      {
        geometry: {
          type: "Polygon",
          coordinates: [
            [
              [122.8670801117507, 40.9901872476559],
              [122.8671560228695, 40.9901541744494],
              [122.866996885425, 40.9899418099605],
              [122.8669209801232, 40.9899710631748],
            ],
          ],
        },
        properties: {
          height: 6, // 多边形高度
        },
      },
      {
        geometry: {
          type: "Polygon",
          coordinates: [
            [
              [122.8666097709528, 40.9900993591307],
              [122.8669893089948, 40.9899302442827],
              [122.8669135304204, 40.989829839658],
              [122.8665264102651, 40.9899988121624],
            ],
          ],
        },
        properties: {
          height: 6, // 多边形高度
        },
      },
      {
        geometry: {
          type: "Polygon",
          coordinates: [
            [
              [122.8668750024418, 40.9904355512604],
              [122.8672545577848, 40.9902663824492],
              [122.8671711911054, 40.990162050582],
              [122.866791641241, 40.9903312023001],
            ],
          ],
        },
        properties: {
          height: 6, // 多边形高度
        },
      },
    ];
    const buildLayer = new mapvgl.ShapeLayer({
      color: "rgba(194, 147, 75, 0.8)", // 柱状图颜色
      enablePicked: true, // 是否可以拾取
      selectedIndex: -1, // 选中项
      selectedColor: "rgba(194, 147, 75, 0.5)", // 选中项颜色
      autoSelect: true, // 根据鼠标位置来自动设置选中项
    });
    mapViewManager.addLayer(buildLayer);
    buildLayer.setData(data);
    mapInstance.setDefaultCursor("default");
  };

  // 文字图层
  const _renderText = (text, lnglat) => {
    const layer = new mapvgl.TextLayer({
      color: "#757576",
      fontFamily: "Microsoft Yahei",
      fontSize: 14,
      flat: false,
      collides: true,
      offset: [0, 0],
      padding: [2, 2],
      margin: [0, 0],
      data: [
        {
          geometry: {
            type: "Point",
            coordinates: [lnglat[0], lnglat[1]],
          },
          properties: {
            text: text, // 展示的文字
          },
        },
      ],
    });
    mapViewManager.addLayer(layer);
  };

  // 渲染 mapvgl Polygon
  const _renderMockBounds = (coordinates) => {
    const data = [
      {
        geometry: {
          type: "Polygon",
          coordinates: [coordinates],
        },
      },
    ];

    const layer = new mapvgl.PolygonLayer({
      lineColor: "rgba(250, 250, 25, 0.6)",
      lineWidth: 2,
      fillColor: "rgba(25, 25, 250, 0.3)",
      data: data,
    });
    mapViewManager.addLayer(layer);
  };

  const _renderMapBounds = () => {
    const data = [
      {
        geometry: {
          type: "LineString",
          coordinates: [
            [122.86124366026955, 40.99395204881801],
            [122.85968148219445, 40.992204898704635],
            [122.85814731732755, 40.99136722870025],
            [122.8576592856406, 40.98930661449181],
            [122.86716468096051, 40.98307195789435],
            [122.87105340526912, 40.98166124404744],
            [122.87726203526744, 40.98800631019741],
            [122.8786209450412, 40.989239377377565],
            [122.8783327335997, 40.991368084656806],
            [122.87624184497095, 40.99268189274696],
            [122.87324070839945, 40.99308212801733],
            [122.86969665529128, 40.993590754630326],
            [122.86553176968076, 40.9927030686492],
            [122.86359170385222, 40.992837701499845],
            [122.86124366026955, 40.99395204881801],
          ],
        },
      },
    ];
    // --wall
    const wallLayer = new mapvgl.WallLayer({
      color: "rgba(50,50,200,1)",
      data: data,
      texture: "src/assets/images/textures/2.jpg",
      enablePreciseMap: true, // 精准贴图模式
      repeatMap: 200,
      height: 20,
    });
    mapViewManager.addLayer(wallLayer);
    return wallLayer;
  };

  // 渲染监控
  const _renderMonitor = () => {
    // icon
    const iconLayer = new mapvgl.IconLayer({
      width: 30,
      height: 30,
      icon: "src/assets/icons/camera.png",
      enablePicked: true, // 是否可以拾取
      selectedIndex: -1, // 选中项
      selectedColor: "#ff0000", // 选中项颜色
      autoSelect: true, // 根据鼠标位置来自动设置选中项
      onClick: _handleMapMarkerClick,
    });

    mapViewManager.addLayer(iconLayer);
    iconLayer.setData([
      {
        geometry: {
          type: "Point",
          coordinates: [122.866107, 40.992044],
        },
        type: "monitor",
      },
      {
        geometry: {
          type: "Point",
          coordinates: [122.865326, 40.991227],
        },
        type: "monitor",
      },
      {
        geometry: {
          type: "Point",
          coordinates: [122.866808, 40.990145],
        },
        type: "monitor",
      },
      {
        geometry: {
          type: "Point",
          coordinates: [122.870976, 40.984141],
        },
        type: "monitor",
      },
      {
        geometry: {
          type: "Point",
          coordinates: [122.87006, 40.982752],
        },
        type: "monitor",
      },
      {
        geometry: {
          type: "Point",
          coordinates: [122.859855, 40.992085],
        },
        type: "monitor",
      },
      {
        geometry: {
          type: "Point",
          coordinates: [122.864087, 40.990605],
        },
        type: "monitor",
      },
      {
        geometry: {
          type: "Point",
          coordinates: [122.866499, 40.988427],
        },
        type: "monitor",
      },
      {
        geometry: {
          type: "Point",
          coordinates: [122.864244, 40.986735],
        },
        type: "monitor",
      },
      {
        geometry: {
          type: "Point",
          coordinates: [122.869587, 40.990415],
        },
        type: "monitor",
      },
    ]);
    return iconLayer;
  };

  // 渲染喇叭
  const _renderBoard = () => {
    // icon
    const iconLayer = new mapvgl.IconLayer({
      width: 30,
      height: 30,
      icon: "src/assets/icons/broadcast.png",
      enablePicked: true, // 是否可以拾取
      selectedIndex: -1, // 选中项
      selectedColor: "#ff0000", // 选中项颜色
      autoSelect: true, // 根据鼠标位置来自动设置选中项
      onClick: _handleMapMarkerClick,
    });

    const mockDatas = [
      [122.865232, 40.990905],
      [122.864989, 40.986991],
      [122.860848, 40.98872],
      [122.862806, 40.991423],
      [122.871098, 40.983771],
      [122.874399, 40.989328],
      [122.871318, 40.987936],
      [122.87147, 40.990836],
    ];

    const data = mockDatas.map((item) => {
      return {
        geometry: {
          type: "Point",
          coordinates: item,
        },
        type: "megaphone",
      };
    });

    mapViewManager.addLayer(iconLayer);
    iconLayer.setData(data);
    return iconLayer;
  };

  // 渲染传感器
  const _renderSensor = () => {
    const sensorLayer = new mapvgl.IconLayer({
      width: 30,
      height: 30,
      icon: "src/assets/icons/sensor.png",
      enablePicked: true, // 是否可以拾取
      selectedIndex: -1, // 选中项
      selectedColor: "#ff0000", // 选中项颜色
      autoSelect: true, // 根据鼠标位置来自动设置选中项
      onClick: _handleMapMarkerClick,
    });

    const mockDatas = [
      [122.863481, 40.990881],
      [122.862784, 40.990575],
      [122.86472, 40.988097],
      [122.866885, 40.98647],
      [122.86861, 40.984305],
      [122.868037, 40.990153],
      [122.869529, 40.989268],
      [122.871308, 40.984126],
      [122.870711, 40.983129],
    ];

    const data = mockDatas.map((item) => ({
      geometry: {
        type: "Point",
        coordinates: item,
      },
      type: "sensor",
    }));

    mapViewManager.addLayer(sensorLayer);
    sensorLayer.setData(data);
    return sensorLayer;
  };

  // 初始化地图
  useEffect(() => {
    mapInit();
  }, []);

  const handleOk = () => {
    setIsModalVisible(false);
  };

  const handleCancel = () => {
    setIsModalVisible(false);
  };

  // 处理地图标记点的点击事件
  const _handleMapMarkerClick = (e) => {
    // 点击事件
    if (e.dataIndex !== -1) {
      // 点击中了图标
      console.log("点击中了", e);
      // 1. 将所点击的点移动到地图中心
      const clickPoint = new BMapGL.Point(
        e.dataItem.geometry.coordinates[0],
        e.dataItem.geometry.coordinates[1]
      );
      mapInstance.panTo(clickPoint);

      const {
        dataItem: { type },
      } = e;
      console.log(type);

      // 2. 弹出提示框
      setIsModalVisible(true);

      // 3. 设置当前点击对象数据
      let data = null;
      if (type === "megaphone") {
        data = {
          url: "megaphone send url",
        };
      } else if (type === "monitor") {
        data = {
          url: "monitor url",
        };
      }else if (type === "sensor") {
        data = {
          temperature: (Math.random() * 40 - 12).toFixed(2),
          humidity: (Math.random() * 48 + 13).toFixed(2)
        };
      }
      setActiveObj({ type, data });
    }
  };

  // modal 关闭
  const handleModalAfterClose = () => {
    console.log("modal AfterClose");
    mapInstance && mapInstance.setTilt(mapInstance.getCurrentMaxTilt());
  };

  const _renderModalTitle = () => {
    switch (activeObj.type) {
      case "none":
        return "";
      case "monitor":
        return "监控";
      case "megaphone":
        return "喇叭";
      case "sensor":
        return "网关";
    }
  };

  // 渲染弹出模态框内容
  const _renderModalContent = () => {
    const { type, data } = activeObj;
    switch (activeObj.type) {
      case "none":
        return "";
      case "monitor":
        return <Player src="http://192.168.10.122/live?app=demo&stream=test" />;
      case "megaphone":
        return <Board />;
      case "sensor":
        return <div>
          <Player src="http://192.168.10.122/live?app=demo&stream=test"></Player>
          <p>温度: { data["temperature"] }</p>
          <p>湿度: { data["humidity"] }</p>
        </div>;
    }
  };

  // 显示/隐藏 监控 图层
  const monitorSwitchChange = (checked) => {
    // console.log('value: ', checked)
    if (views.monitor) {
      mapViewManager.removeLayer(monitorLayer)
    } else {
      mapViewManager.addLayer(monitorLayer)
    }
    setViews({
      monitor: checked,
      sensor: views.sensor,
      megaphone: views.megaphone
    })
  };

  // 显示/隐藏 喇叭图层
  const megaphoneSwitchChange = (checked) => {
    if (views.megaphone) {
      mapViewManager.removeLayer(megaphoneLayer)
    } else {
      mapViewManager.addLayer(megaphoneLayer)
    }
    setViews({
      megaphone: checked,
      monitor: views.monitor,
      sensor: views.sensor
    })
  };

  // 显示/隐藏 传感器图层（网关）
  const sensorSwitchChange = (checked) => {
    if (views.sensor) {
      mapViewManager.removeLayer(sensorLayer)
    } else {
      mapViewManager.addLayer(sensorLayer)
    }
    setViews({
      sensor: checked,
      monitor: views.monitor,
      megaphone: views.megaphone
    })
  };

  return (
    <div className={styles.Container}>
      <div className={styles.Map} id="map-container" ref={mapRef}></div>
      <div className={styles.ToolBar}>
        <div className={styles.ToolBarItem}>
        监控：<Switch defaultChecked onChange={monitorSwitchChange} />
        </div>
        <div className={styles.ToolBarItem}>
        喇叭：<Switch defaultChecked onChange={megaphoneSwitchChange} />
        </div>
        <div className={styles.ToolBarItem}>
        网关：<Switch defaultChecked onChange={sensorSwitchChange} />
        </div>
      </div>

      {/* 模态框 */}
      <Modal
        title={_renderModalTitle()}
        visible={isModalVisible}
        onOk={handleOk}
        onCancel={handleCancel}
        afterClose={handleModalAfterClose}
        maskClosable={false}
        destroyOnClose={true}
        okText="确认"
      >
        {_renderModalContent()}
      </Modal>
    </div>
  );
};

export default MapV;
